package com.huiyou.adminapi.service;

import com.huiyou.adminapi.common.model.Goods;
import com.huiyou.adminapi.common.model.Product;
import com.huiyou.adminapi.repository.GoodsRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService {

    private final GoodsRepository goodsRepository;
    private final ProductService productService;

    @Autowired
    public GoodsService(GoodsRepository goodsRepository, ProductService productService) {
        this.goodsRepository = goodsRepository;
        this.productService = productService;
    }

    public Page<Goods> findAll(String name, Pageable pageable) {
        return this.goodsRepository.findByNameContainingOrderByProductionTimeDesc(name, pageable);
    }

    public Goods findById(String id) {
        return this.goodsRepository.findById(id).orElse(null);
    }

    public void save(Goods goods) {
        List<Goods> goodsList = null;
        if(goods.getId() == null){
            goodsList = goodsRepository.findByName(goods.getName());
        }else{
            goodsList = goodsRepository.findByNameAndIdIsNot(goods.getName(), goods.getId());
        }
        if(goodsList.size() > 0){
            throw new RuntimeException("商品名称已存在!");
        }

        Product product = productService.findById(goods.getProId());
        product.setName(product.getName());
        this.goodsRepository.save(goods);
    }

    public void deleteById(String id) {
        this.goodsRepository.deleteById(id);
    }

    public List<Goods> findByProId(String id){

        return this.goodsRepository.findByProId(id);
    }

}
